<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeGridProps } from '#/adapter/vxe-table'
import TableAction from '#/components/TableAction/index.vue'
import { findNode, treeToList } from '#/helper/treeHelper'
import { usePagePermission } from '#/hooks/usePermission'
import { useTableCURD } from '#/hooks/useTableList'
import { Page } from '@vben/common-ui'
import { $t } from '@vben/locales'
import { Button, message } from 'ant-design-vue'
import { unref } from 'vue'
import AddEditModal from './components/AddEditModal.vue'
import { columns, formSchema } from './data/table'
import type { TableListItem } from './use/api'
import { PageApi } from './use/api'
import { PAGE_AUTH_CODE_PREFIX, PAGE_NAME } from './use/config'

const formOptions: VbenFormProps = {
    schema: formSchema
}

const gridOptions: VxeGridProps<any> = {
    columns,
    pagerConfig: {
        enabled: false
    },
    treeConfig: {
        parentField: 'pid',
        rowField: 'id',
        transform: true
    },
    expandConfig: {
        reserve: true
    },
    rowConfig: {
        keyField: 'id'
    },
    proxyConfig: {
        ajax: {
            query: async (_, formValues) => {
                const items = await PageApi.getPageList(formValues as any)

                return {
                    items,
                    total: items.filter((item) => item.pid === 0).length
                }
            }
        }
    }
}

// const expandedKeys = ref<number[]>([])

/**
 * 表格配置
 */
const {
    Grid,
    GridApi,
    FormModal,
    add: handleCreate,
    edit: handleEdit,
    del: handleDelete,
    handleSuccess,
    modalType
} = useTableCURD<TableListItem>({
    formOptions,
    gridOptions,
    // gridEvents: {
    //     toggleTreeExpand() {
    //         expandedKeys.value = GridApi.grid.getTreeExpandRecords().map((item) => item.id)
    //     }
    // },

    modalOptions: {
        connectedComponent: AddEditModal
    },
    delApi: PageApi.delete
})

// 权限配置
const { getPagePermissionKey, hasPagePermission } = usePagePermission(PAGE_AUTH_CODE_PREFIX)

function handleCreateFix() {
    handleCreate({
        treeData: GridApi.grid.getTableData().tableData
    })
}

/**
 * table 操作
 * @param record
 */
function getActions(record: TableListItem) {
    const arr: any[] = [
        {
            icon: 'clarity:plus-circle-line',
            tooltip: $t('common.formModal.addTitle', {
                title: unref(PAGE_NAME)
            }),
            auth: getPagePermissionKey('add'),
            onClick: () => {
                handleCreate({
                    pid: record?.id,
                    treeData: GridApi.grid.getTableData().fullData
                })
            }
        },
        {
            icon: 'clarity:note-edit-line',
            tooltip: $t('common.edit'),
            onClick: () => {
                handleEdit(record, {
                    treeData: GridApi.grid.getTableData().fullData
                })
            },
            auth: getPagePermissionKey('edit')
        },
        {
            icon: 'ant-design:delete-outlined',
            color: '#bb1b1b',
            tooltip: $t('common.delete'),
            popConfirm: {
                title: $t('page.system.children.menu.children.action.deleteTip', {
                    title: $t(record.title || '')
                }),
                placement: 'left',
                onConfirm: () => {
                    delSelfAllSon(record)
                }
            },
            auth: getPagePermissionKey('delete')
        }
    ]

    return arr
}

// const isExpandAll = ref(false)
// function toggleExpandAll() {
//     GridApi?.grid.setAllTreeExpand(!isExpandAll.value)

//     isExpandAll.value = !isExpandAll.value
// }

/**
 * 删除自己和所有子菜单
 */
async function delSelfAllSon(record: TableListItem) {
    const treeData = GridApi.grid.getTableData().tableData

    const curNode = findNode(treeData, (v) => v.id === record.id)

    if (curNode) {
        const arr = treeToList([curNode]).map((v: any) =>
            handleDelete(v, { isSuccessCallback: false, isShowToast: false })
        )

        const res = await Promise.all(arr)
        GridApi.reload()
        message.success($t('common.deleteSuccess'))

        return res
    } else {
        return handleDelete(record)
    }
}
</script>

<template>
    <Page auto-content-height>
        <Grid>
            <template #toolbar-tools>
                <view class="flex gap-2">
                    <Button v-if="hasPagePermission('add')" type="primary" @click="handleCreateFix">
                        {{ $t('common.formModal.addTitle', { title: PAGE_NAME }) }}
                    </Button>
                    <!-- <Button @click="toggleExpandAll">
                        {{ isExpandAll ? $t('common.collapseAll') : $t('common.expandAll') }}
                    </Button> -->
                </view>
            </template>
            <template #action="{ row }">
                <TableAction :actions="getActions(row)" />
            </template>
        </Grid>
        <FormModal @success="handleSuccess" :modal-type="modalType" />
    </Page>
</template>
